import requests
from bs4 import BeautifulSoup
from sql_utils import DatabaseManager

manager = DatabaseManager()


def fetch_movie_info_from_file():
    movie_list = []
    # 读取文件
    for i in range(1, 11):
        # 使用BeautifulSoup解析HTML
        text = requests.get('https://ssr1.scrape.center/page/{}'.format(i)).text
        soup = BeautifulSoup(text, 'lxml')

        # 假设电影信息存储结构（需要根据你的HTML结构调整）
        movies = soup.find_all('div', class_='el-card item m-t is-hover-shadow')


        for movie in movies:
            # 提取电影信息（根据HTML结构调整）
            title = movie.find('h2').get_text(strip=True) if movie.find('h2') else ''
            # 假设country在特定的class中，这里可能需要调整
            country = movie.find('div', class_='m-v-sm info').find('span').get_text(strip=True) if movie.find('div', class_='m-v-sm info').find('span') else ''
            duration = movie.find('div', class_='m-v-sm info').find_all('span')[2].string if len(
                movie.find('div', class_='m-v-sm info').find_all('span')) > 2 else ''

            # 注意：这里的release_date和rating提取方式可能需要调整，这里只是示例
            movie_info = movie.find_all('div', class_='m-v-sm info')
            try:
                release_date = movie_info[1].find('span').string
            except:
                release_date = "上映时间缺失"
                pass
            buttons = movie.find_all('button')
            rating = [button.find('span').string for button in buttons if button.find('span')]

            movie_list.append({
                '电影名称': title,
                '国家': country,
                '时长': duration,
                '上映时间': release_date,
                '剧情类型': rating
            })

    return movie_list


# 提取前10页的电影信息
movies = fetch_movie_info_from_file()
for movie in movies:
    format_sql = r'''INSERT INTO movies (movie_name, country, duration, release_date, rating)
        VALUES ("{}", "{}", "{}", "{}", "{}")'''
    final_sql = format_sql.format(movie['电影名称'], movie['国家'], movie['时长'], movie['上映时间'],
                                   movie['剧情类型'])
    print(final_sql)
    manager.execute(final_sql)


manager.commit_and_close()